package com.ksl.kinglockguard.network.appupdate;

import org.json.JSONException;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Toast;

import com.ksl.kinglockguard.R;
import com.ksl.kinglockguard.data.Constants;
import com.ksl.kinglockguard.data.SharePreferenceSdkData;
import com.ksl.kinglockguard.widget.common.UpdateDialog;
import com.lsk.open.core.MyLog;
import com.lsk.open.core.net.NetConnectTask;


public class UpdateAppTaskListener implements NetConnectTask.TaskListener {

	private static final int MSG_NOTIFY = 0;
	private static final int MSG_ERROR = 1;
	public static final int NOTIFY_TYPE_DIALOG = 2;
	public static final int NOTIFY_TYPE_NOTIFICATION = 1;
	private Context mContext;
	private Handler mUpdateHandler;
	private int notifyType;
	private UpdateDialog updateDialog;
	private Dialog loadingDialog;

	private class UpdateHandler extends Handler {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			int what = msg.what;
			switch (what) {
			case MSG_ERROR:
				if (loadingDialog != null) {
					loadingDialog.dismiss();
				}
				
				if (notifyType == NOTIFY_TYPE_DIALOG) {
					Toast.makeText(mContext, R.string.lock_network_error_no_net_tip, Toast.LENGTH_SHORT).show();
					MyLog.i("jyh", "~~~~~~~//notifyType == NOTIFY_TYPE_DIALOG~~~~~~~~~");
				}
				break;
			case MSG_NOTIFY:
				if (loadingDialog != null) {
					loadingDialog.dismiss();
				}
				
				AppUpdateInfo appUpdateInfo = (AppUpdateInfo) msg.obj;
				String downloadUrl = appUpdateInfo.getDownloadUrl();
				
				if (notifyType == NOTIFY_TYPE_NOTIFICATION) {			//程序自动检查更新
					if (downloadUrl == null || "NA".equals(downloadUrl)) {
						return;
					}
					Intent appUpdateService = new Intent(mContext,
							AppUpdateService.class);
					appUpdateService.putExtra("url", downloadUrl);
					appUpdateService.putExtra("type", Constants.APK_TYPE);
					long packageSize = appUpdateInfo.getPackageSize();
//MyLog.d("update","UpdateHandler----------------packageSize：　" + packageSize);
					appUpdateService.putExtra("fileLength",packageSize);
					if (appUpdateInfo.getDownloadType() == AppUpdateInfo.DOWNLOAD_TYPE_AUTO) {		//静默下载
						appUpdateService.putExtra("downloadNow", true);
						appUpdateService.putExtra(
								"showDownloadingNotification", false);
						appUpdateService.putExtra("showInstallNotification",
								true);
						appUpdateService.putExtra("installNow", false);
					} else {
						appUpdateService.putExtra("downloadNow", false);
						appUpdateService.putExtra(
								"showDownloadingNotification", true);
						appUpdateService.putExtra("showInstallNotification",
								false);
					}
					mContext.startService(appUpdateService);
				} else if(notifyType == NOTIFY_TYPE_DIALOG && loadingDialog != null){		//用户手动更新
					if (downloadUrl == null || "NA".equals(downloadUrl)) {
						Toast.makeText(mContext, "此版本已是最新版本，无需更新", Toast.LENGTH_SHORT).show();
						return;
					}
					showUpdateDialog(appUpdateInfo);
				}

				break;
			}
		}
	}

	public void showUpdateDialog(final AppUpdateInfo appUpdateInfo) {
		updateDialog = new UpdateDialog(this.mContext,
				appUpdateInfo.getUpdateType());
		updateDialog.setUpdateInfo(appUpdateInfo.getVersionName(),
				appUpdateInfo.getPackageSize(), appUpdateInfo.getDetail());
		updateDialog.setBtnOkListener(new View.OnClickListener() {
			public void onClick(View paramAnonymousView) {
				Intent appUpdateService = new Intent(
						UpdateAppTaskListener.this.mContext,
						AppUpdateService.class);
				appUpdateService.putExtra("url", appUpdateInfo.getDownloadUrl());
				appUpdateService.putExtra("type", Constants.APK_TYPE);
				appUpdateService.putExtra("downloadNow", true);
				appUpdateService.putExtra("showDownloadingNotification", true);
				appUpdateService.putExtra("showInstallNotification", false);
				long packageSize = appUpdateInfo.getPackageSize();
				MyLog.d("update","showUpdateDialog----------------packageSize：　" + packageSize);
				appUpdateService.putExtra("fileLength",
						packageSize);
				mContext.startService(appUpdateService);
				updateDialog.dismiss();
			}
		});
		updateDialog.setBtnLaterListener(new View.OnClickListener() {
			public void onClick(View paramAnonymousView) {
				updateDialog.dismiss();
			}
		});
		updateDialog.setBtnCancleListener(new View.OnClickListener() {
			public void onClick(View paramAnonymousView) {
				updateDialog.dismiss();
			}
		});
		updateDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
					public void onDismiss(
							DialogInterface paramAnonymousDialogInterface) {
					}
				});
		try {
			updateDialog.show();
			return;
		} catch (Exception e) {
			e.printStackTrace();
			MyLog.d("update","onPostExecute---show dialog exception: "+ e.getMessage());
		}
	}

	public UpdateAppTaskListener(Context paramContext, int paramInt,
			Dialog dialog) {
		this.notifyType = paramInt;
		this.mContext = paramContext;
		this.mUpdateHandler = new UpdateHandler();
		this.loadingDialog = dialog;
	}

	@Override
	public void onNoNetworking() {
		mUpdateHandler.sendEmptyMessage(MSG_ERROR);
		MyLog.d("lijc", "onNoNetworking()");
	}

	@Override
	public void onNetworkingError() {
		mUpdateHandler.sendEmptyMessage(MSG_ERROR);
		MyLog.d("lijc", "onNetworkingError()");
	}

	@Override
	public void onPostExecute(byte[] bytes) {
		try {
			AppUpdateInfo appUpdateInfo = new AppUpdateInfo(new String(bytes));
			MyLog.d("update", "UpdateAppTaskListener---onPostExecute ----bytes: " + new String(bytes));
			Message msg = new Message();
			msg.what = MSG_NOTIFY;
			msg.obj = appUpdateInfo;
			mUpdateHandler.sendMessage(msg);
			SharePreferenceSdkData.setLastCheckUpdateTime(mContext,System.currentTimeMillis());
			return;
		} catch (JSONException e) {
			mUpdateHandler.sendEmptyMessage(MSG_ERROR);
			MyLog.d("lijc", "JSONException");
			MyLog.d("update","UpdateAppTaskListener---onPostExecute ----JSONException: " + e.getMessage());
			e.printStackTrace();
		}
	}

}
